package com.ruoyi.common;

import com.ruoyi.common.distributeLock.context.ZkContext;
import lombok.Data;
import org.apache.zookeeper.*;
import com.ruoyi.common.distributeLock.callback.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
/**
 * @author gim 2023/4/19 9:36
 */
@Data
public class ZkLockHelper  {
    private ThreadLocal<String> path;
    private ZkCallback zkCallback;
    private final String lockPath="/ruoyi/lockItem";

    ZooKeeper zooKeeper;
    String threadName;

    private CountDownLatch cd;
    private String pathName;

    ZkContext zkContext;

    public void tryLock(){
        try{
            zooKeeper.create(lockPath,
                    threadName.getBytes(StandardCharsets.UTF_8),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, //权限：允许读和写
                    CreateMode.EPHEMERAL_SEQUENTIAL,//临时顺序队列
                    zkCallback, //回调处理类
                    zkContext); //上下文
            cd.await();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }


    public void unLock(){
        try{
            zooKeeper.delete("/ruoyi"+zkContext.getPath(),-1);
            System.out.println(threadName+" finish work");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
